//
//  EGAViewController.m
//  EGA_Archives_iOS
//
//  Created by kitinat on 11/5/12.
//  Copyright (c) 2012 EGA. All rights reserved.
//  Test adding comments by asisunyapoth
//


#import "EGAViewController.h"
#import "EGAAppDelegate.h"
#import "EGAEmployeeInfo.h"
#import "mainEGAViewController.h"
#import "ARC_DB.h"
#import "EGAUtility.h"
@interface EGAViewController ()

@end

@implementation EGAViewController

-(EGAAppDelegate*)appDelegate
{
    return  (EGAAppDelegate*)[[UIApplication sharedApplication] delegate];
}

- (void)ShowAlert:(NSString *)strAlet
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"ไม่สามารถเชื่อมต่อ Internet" message:@"กรุณาเช็คการเชื่อมต่อ" delegate:self cancelButtonTitle:@"ตกลง" otherButtonTitles: nil];
    [alert show];
}
NSDictionary * arrUserInfo;
NSDictionary *empInfoDB;
NSString *servicePath;
- (void)viewDidLoad
{
    
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    //*******************get user info to DB and delegate**********************************//
    
    
    ARC_DB * DB = [[ARC_DB alloc]init];
    BOOL flag=[DB isHasUserInfoDB];
    //NSLog(flag ? @"Y":@"No");
    // เช็คว่า เคยเข้าระบบรึยังถ้าใช่ ไม่ต้อง login
    if (flag)
    {
        arrUserInfo = [DB getUserData];
        empInfoDB=[DB getUserData];
        [[self appDelegate] fetchEmployeeInfo:empInfoDB];
        mainEGAViewController*mainController  = [[mainEGAViewController alloc]initWithNibName:@"mainEGAViewController" bundle:[NSBundle mainBundle]];
        [self.view addSubview:mainController.view];
    }
    else
    {
       
    }
    //*******************get user info to DB and delegate**********************************//

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    //    [_txt_username release];
    //    [_txt_password release];
    //    [_lbl_alert release];
    //    [_tbt_submit release];
        [super dealloc];
}

/*
- (IBAction)login:(id)sender {
    
    if (![[self appDelegate] connectedToInternet]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"ไม่สามารถเชื่อมต่อ Internet" message:@"กรุณาเช็คการเชื่อมต่อ" delegate:self cancelButtonTitle:@"ตกลง" otherButtonTitles: nil];
        [alert show];
        return;
    }
    
	NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: loginURL]];
    
	NSString *post = [NSString stringWithFormat:@"username=%@%@&password=%@",
                      _txt_username.text,@"@ega.or.th",
                      _txt_password.text];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
	
	//Data returned by WebService
	NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
    if ([returnData length] == 0) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"ไม่สามารถเชื่อมต่อ server" message:@"กรุณาเช็คการเชื่อมต่อ" delegate:self cancelButtonTitle:@"ตกลง" otherButtonTitles: nil];
        [alert show];
        return;
    }
    [self fetchData:returnData];
    
}
*/
- (IBAction)login:(id)sender {
    if (![[self appDelegate] connectedToInternet]) {
        [self ShowAlert:@""];
        return;
    }
    
    
//	//NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: loginURL]];
//    servicePath = [NSString stringWithFormat:@"http://%@CreateUserSession.ashx",serviceUrl];
//    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: servicePath]];
//    
//    
//
//	NSString *post = [NSString stringWithFormat:@"username=%@%@&password=%@",
//                      _txt_username.text,@"@ega.or.th",
//                      _txt_password.text];
//    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
//    [request setHTTPMethod:@"POST"];
//    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
//    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//    [request setHTTPBody:postData];
//	//Data returned by WebService
//	
//    NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
    
    ////////////////new
    EGAUtility * Util = [[EGAUtility alloc]init];
    NSString *post = [NSString stringWithFormat:@"ws=CreateUserSession.ashx&username=%@%@&password=%@",
                      _txt_username.text,@"@ega.or.th",
                      _txt_password.text];
    NSData *returnData =[Util getDataFromService:post];
    ////////////////new

    if ([returnData length] == 0) {
        
        [self ShowAlert:@""];
        return;
    }
    //    NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
    //    NSLog(returnString);
    [self fetchData:returnData];
}

#define jsonIsSuccess @"IsSuccess"
#define jsonResponseText @"ResponseText"
#define jsonResponseEmployeeInfo @"EmployeeInfo"
#define jsonResponseAbsentInfo @"AbsentTypeInfo"
#define jsonResponseTypeName @"ResponseTypeName"
#define segueIDAbsent @"AbsentMain"
-(NSInteger)getJSONInt:(NSObject*)obj
{
    return [(NSNumber*)obj intValue];
}

-(Boolean)getJSONBoolean:(NSObject*)obj
{
    return ([(NSNumber*)obj intValue] == true)?NO:YES;
}


-(void)fetchData:(NSData*)jsonData
{
    NSError *error;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
   // NSLog(@"x:%@",[json objectForKey:@"IsSuccess"]);
    
    NSString *chkIsSuccess=[json objectForKey:@"IsSuccess"];
    
    // BOOL isSuccess = [self getJSONBoolean:[json objectForKey:jsonIsSuccess]];
    // NSString *isSuccess=[json objectForKey:@"EmpID"];
    
    if (![chkIsSuccess isEqualToString:@"True"])
    {
    //if (!isSuccess) {
        //fail
        [self.lbl_alert setHidden:NO];
    }
    else {
        //success
        [self.lbl_alert setHidden:YES];
        
        // _lbl_alert.text=@"test";
        
        //  NSData *jsonResponseTextData = [[json objectForKey:jsonResponseText] dataUsingEncoding:NSUTF8StringEncoding];
        //   NSDictionary *jsonEmployeeDataDictionary = [NSJSONSerialization JSONObjectWithData:jsonResponseTextData options:kNilOptions error:&error];
        [[self appDelegate] fetchEmployeeInfo:json];
        //[self performSegueWithIdentifier:segueIDAbsent sender:self];
        mainEGAViewController*mainController  = [[mainEGAViewController alloc]initWithNibName:@"mainEGAViewController" bundle:[NSBundle mainBundle]];
        // [self presentViewController:mainController animated:YES completion:^{
        //}];
        
        //*************************************************************************************//
        ARC_DB * DB = [[ARC_DB alloc]init];
        // NSString *empID = [NSString stringWithFormat:@"%@",self.appDelegate.employeeInfo.EmpID];
        //เก็บ userinfo ลง DB
        // *** ต้องล้างค่าไหม?
        [DB saveUserData:[NSString stringWithFormat:@"%@",self.appDelegate.employeeInfo.EmpID] RoleID:[NSString stringWithFormat:@"%@",self.appDelegate.employeeInfo.RoleID] RoleName:[NSString stringWithFormat:@"%@",self.appDelegate.employeeInfo.RoleName] Title:[NSString stringWithFormat:@"%@",self.appDelegate.employeeInfo.Title] FirstNameTH:[NSString stringWithFormat:@"%@",self.appDelegate.employeeInfo.FirstNameTH] LastNameTH:[NSString stringWithFormat:@"%@",self.appDelegate.employeeInfo.LastNameTH] SectorName:@"gadd"  IsHeadEGA:@""];
        //*******************get user info to DB and delegate**********************************//
        arrUserInfo = [DB getUserData];
        empInfoDB=[DB getUserData];
        [[self appDelegate] fetchEmployeeInfo:empInfoDB];
        //*******************get user info to DB and delegate**********************************//
        
        
        [self.view addSubview:mainController.view];
    }
}




@end

        
        
        
        
 